package com.cskaoyan.controller;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.cskaoyan.anno.HashPasswordAnno;
import com.cskaoyan.bean.BaseRespVo;
import com.cskaoyan.bean.User;
import com.cskaoyan.bean.auth.bo.*;
import com.cskaoyan.bean.auth.vo.UserInfo;
import com.cskaoyan.bean.auth.vo.WXAuthLoginVo;
import com.cskaoyan.config.aliyun.AliyunComponent;
import com.cskaoyan.config.shiro.CustomToken;
import com.cskaoyan.service.RedisService;
import com.cskaoyan.service.UserService;
import com.cskaoyan.util.IpAddressUtil;
import com.cskaoyan.util.StringUtils;
import com.fasterxml.jackson.databind.ser.Serializers;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;

/**
 * @author wangdezhao
 * @date 2021/6/7
 * @description
 */
@RequestMapping("wx/auth")
@RestController
public class WXAuthController {
    @Autowired
    UserService userService;
    @Autowired
    RedisService redisService;
    @Autowired
    AliyunComponent aliyunComponent;

    @HashPasswordAnno
    @RequestMapping("login")
//    @RequiresPermissions("/admin/auth/login")
    public BaseRespVo login(@RequestBody WXAuthLoginBo wxLoginBO,HttpServletRequest request) {
        // vo
        WXAuthLoginVo wxAuthLoginVo = new WXAuthLoginVo();
        // vo 成员变量
        UserInfo userInfo = new UserInfo();

        Subject subject = SecurityUtils.getSubject();
        Serializable id = subject.getSession().getId();
        String username = wxLoginBO.getUsername();
        String password = wxLoginBO.getPassword();
        System.out.println(password);
        CustomToken token = new CustomToken(username, password, "user");
        try {
            subject.login(token);
            User user = userService.selectUser(username);
            wxAuthLoginVo.setToken((String) id);
            wxAuthLoginVo.setTokenExpire(null); // todo 过期时间
            userInfo.setNickName(username);
            userInfo.setAvatarUrl(user.getAvatar());
            wxAuthLoginVo.setUserInfo(userInfo);
        } catch (Exception e) {
            return BaseRespVo.fail("账号密码错误");
        }
        String remoteAddr = request.getRemoteAddr();
        userService.getLastLoginTime(username);
        userService.getLastLoginIp(remoteAddr,username);
        return BaseRespVo.ok(wxAuthLoginVo);
    }

    @RequestMapping("logout")
    public BaseRespVo logout() {
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.logout();
        } catch (Exception e) {
            return BaseRespVo.fail();
        }
        return BaseRespVo.ok("成功");
    }

    @PostMapping("regCaptcha")
    public BaseRespVo regCaptcha(@Validated @RequestBody RegCaptchaBo bo, BindingResult bindingResult) {
        String mobile = bo.getMobile();
        String veryCode = StringUtils.getVeryCode();
        //配置文件整合
        CommonResponse response = aliyunComponent.sendMsg(mobile, veryCode);

        if (response != null) {
            redisService.set(mobile + ":veryCode", veryCode);//存入redis
            return BaseRespVo.ok();//成功
        }
        /*String accessKeyId = "防骚扰";
        String accessSecret = "防骚扰";
        DefaultProfile profile = DefaultProfile.getProfile("cn-qingdao", accessKeyId, accessSecret);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("PhoneNumbers", mobile);
        request.putQueryParameter("SignName", "stone4j");
        request.putQueryParameter("TemplateCode", "SMS_173765187");
        request.putQueryParameter("TemplateParam", "{\"code\": \""+ veryCode +"\"}");
        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
            redisService.set(mobile + ":veryCode", veryCode);//存入redis
            return BaseRespVo.ok();//成功
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }*/
        return BaseRespVo.fail("获取验证码失败");

    }
    @HashPasswordAnno
    @PostMapping("reset")
    public BaseRespVo reset(@RequestBody UserAuthResetBo bo) {
        String veryCode = bo.getCode();
        String mobile = bo.getMobile();
        String cacheVeryCode = (String) redisService.get(mobile + ":veryCode");

        if (!veryCode.equals(cacheVeryCode)) {
            return BaseRespVo.fail("验证码错误");
        }
        userService.changePassword(bo);
        return BaseRespVo.ok();

    }

    @RequestMapping("register")
    @HashPasswordAnno
    public BaseRespVo regCaptcha(@RequestBody WXAuthRegisterBo registerBo){
        String mobile = registerBo.getMobile();
        String code = registerBo.getCode();
        String cacheVeryCode = (String) redisService.get(mobile + ":veryCode");
        if (code.equals(cacheVeryCode)){
            int effectedRows = userService.insertUser(registerBo);
            if (effectedRows != 1){
                return BaseRespVo.fail("注册失败,请重试");
            }
        }
        return BaseRespVo.ok("注册成功!!!");
    }
}
